<template>
  <div :class="{editing: isEdited }">
    <div class="view">
      <!-- 选择某条备忘 -->
      <!-- v-model 绑定是否选中 -->
      <input class="toggle" type="checkbox" @change="updateChecked($event.target.checked)">

      <!-- 双击可操作备忘 -->
      <label @dblclick="editTodo()">{{ title }}</label>

      <!-- 删除某条备忘 -->
      <button class="destroy" @click="removeTodo()"></button>
    </div>

    <input class="edit" type="text" v-model="editingTitle" v-autofocus v-if="isEdited"
           @blur="doneEdit()"
           @keyup.enter="doneEdit()"
           @keyup.esc="cancelEdit()"
    >
  </div>
</template>

<script>
import confirmDialog from "../utils/confirm"
export default {
  // name: "TodoItem",
  data() {
    return {
      // is editing
      isEdited: false,
      // content of editing
      editingTitle: "",
    }
  },

  props: {
    // 备忘内容
    title: {
      type: String,
      default: ""
    },

    // 备忘勾选（已完成）状态
    completed: {
      type: Boolean,
      default: false,
    },
  },

  methods: {
    // 编辑备忘
    editTodo() {
      this.editingTitle = this.title;
      this.isEdited = true;
    },

    // 确认修改备忘
    doneEdit() {
      if(this.isEdited) {
        this.$emit("update:title", this.editingTitle);
        this.isEdited = false;
      }
    },

    // 取消修改备忘
    cancelEdit() {
      this.isEdited = false;
    },

    updateChecked(completed) {
      this.$emit("update:completed", completed);
    },

    removeTodo() {
      confirmDialog({
        text: "Are you sure to delete?"
      }).then(res => {
        // 用户点击确认
        console.log("delete confirmed: " + res);
        this.$emit("delete");
      }).catch(() => {
        // 用户点击取消
        console.log("cancel delete");
      })
    }
  },

  directives: {
    autofocus: {
      // 被绑定元素插入父节点时调用
      inserted: function (el) {
        // el: 指令所绑定的元素，可以用来直接操作 DOM
        el.focus();
      }
    }
  }
}
</script>

<style>
.todo-list li .editing .view{
  display: none;
}
.todo-list li .editing .edit{
  display: block;
  width: 506px;
  padding: 12px 16px;
  margin: 0 0 0 43px;
}
</style>